package com.foreknow.controller;

import com.foreknow.bean.Guestbook;
import com.foreknow.service.GuestbookService;
import com.foreknow.service.impl.GuestbookServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.Date;

public class upd extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String method = req.getParameter("q");
        if("edit".equals(method)) {
            edit(req,resp);
        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("text/html;charset=utf-8");
        //设置客户端向服务器端请求的字符编码集为utf-8
        req.setCharacterEncoding("utf-8");
        PrintWriter out = resp.getWriter();
        Guestbook gb = new Guestbook();
        gb.setId(Integer.parseInt(req.getParameter("id")));
        gb.setName(req.getParameter("name"));
        gb.setPhone(req.getParameter("phone"));
        gb.setEmail(req.getParameter("email"));
        gb.setTitle(req.getParameter("title"));
        gb.setContent(req.getParameter("content"));
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        gb.setCreatedtime(simpleDateFormat.format(new Date()));
        GuestbookService service = new GuestbookServiceImpl();
        boolean isRight=service.update(gb);
        if(isRight){
            req.getRequestDispatcher("/user/manager?q=list").forward(req,resp);
        }else {
            out.println("error......");
        }

    }

    protected void edit(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("text/html;charset=utf-8");
        String id = req.getParameter("id");
        GuestbookService service = new GuestbookServiceImpl();
        Guestbook guestbook=service.queryById(Integer.parseInt(id));
        if (guestbook!=null){
            req.setAttribute("guestbook",guestbook);
            req.getRequestDispatcher("/update.jsp").forward(req, resp);
        }else {
            System.out.println("查询错误");
        }
    }
}
